package com.yindong.camera.slice.init;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.Image;
import ohos.media.image.common.ImageFormat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageService implements Runnable{

    private static final HiLogLabel LOG = new HiLogLabel(HiLog.LOG_APP, 00201, ImageService.class.getName());

    private final Image myImage;
    private final File myFile;

    ImageService(Image image, File file) {
        myImage = image;
        myFile = file;
    }

    @Override
    public void run() {
        Image.Component component = myImage.getComponent(ImageFormat.ComponentType.JPEG);
        byte[] bytes = new byte[component.remaining()];
        component.read(bytes);
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(myFile);
            output.write(bytes); // 写图像数据
        } catch (IOException e) {
            HiLog.error(LOG, "save picture occur exception!");
        } finally {
            myImage.release();
            if (output != null) {
                try {
                    output.close(); // 关闭流
                } catch (IOException e) {
                    HiLog.error(LOG, "image release occur exception!");
                }
            }
        }
    }
}
